package chapter07._02_CatchException;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Scanner;

/**
 * @Description: 分析堆栈轨迹元素
 * @LastDate: 2020/11/1
 */
public class Test06_AnalyzeStackTrace {

    public static void main(String[] args) {
        //AnalyzeStackTrace.print();
        /*try (var in = new Scanner(System.in)) {
            System.out.print("Enter n:");
            int n = in.nextInt();
            factorial(n);
        }*/
    }

    /*
     * @Description: 调用 printStackTrace 访问堆栈轨迹的文本信息
     */
    public static void print() {
        var t = new Throwable();
        var out = new StringWriter();
        t.printStackTrace(new PrintWriter(out));
        String desc = out.toString();
        System.out.println(desc);
    }

    /*
     * @Description: cal the factorial of a n
     * @Param n a non-negative integer
     * @return n! = 1 * 2 * ... * n
     */
    public static int factorial(int n) {
        System.out.println("factorial(" + n + "):");
        /*
        * 另外一种打印堆栈轨迹的灵活方法是
        * 使用StackWalker 生成一个StackWalker.StackFrame实例流
        * 流里的每一个frame分别描述一个stack frame
        * */
        var walker = StackWalker.getInstance();
        /*
        * 使用walker.forEach(frame-> analyze frame)
        * or in a lazy way
        * walker.walk(stream -> process stream)
        * */
        walker.forEach(System.out::println);

        int r;
        if (n <= 1) r = 1;
        else r = n * factorial(n - 1);
        System.out.println("return " + r);
        return r;
    }
}
